<template>
	<view class="body-view">
		<!--导航和状态栏-->
		<view class="state-navigation">
			<view class="slim_header_navigation d-flex a-center j-center" >
				<view class="left_box" @tap="goBack">
					<image src="/static/center/back.png" class="back"></image>
				</view>
				<view class="title">热量和体重</view>
				<view class="right_box d-flex a-center j-center">
					<!--
					<i class="icon icon-fenxiang" style="font-size: 60rpx; color: #000000;"></i>
					-->
					<image src="/static/image/share.png" class="share-image"></image>
				</view>
			</view>
		</view>
		<!-- 顶部位置占位 -->
		<view style="height:calc(100rpx + var(--status-bar-height));"></view>
		<view class="menu-tabs d-flex a-center">
			<view v-for="(item,index) in tabs" class="menu-tabs-bottom">
				<view @tap="changeTabs(index)" :class="`menu-tabs-text ${index==menuSelect?'menu-select':''}`">{{item}}</view>
				<view v-if="index==menuSelect" class="menu-tabs-background"></view>
			</view>
		</view>
		<swiper class="swiper" circular :disable-touch="true" :current="menuSelect" @change="changeSwiper">
			<!--数据-->
			<swiper-item>
				<pullScroolView
					class="scroll-data"
					ref="scroll" 
					:back-top="false" 
					:pullDown="dataRefresh" 
					:pullUp="scrolltolower">
					<template v-for="(item, index) in dataPageData.list" :key="index">
						<view v-if="isBreak(index).show" class="data-content">
							<view class="data-content-date">{{isBreak(index).title}}</view>
							<view class="data-content-null d-flex a-center j-center">
								<view class="left-null-text">{{isBreak(index).days>1?`共${isBreak(index).days}天未记录`:`当日未记录`}}</view>
							</view>
						</view>
						<view v-if="item.rest==null" class="data-content">
							<view class="data-content-date">{{lastTwoDays(item.recordDate)}}</view>
							<view class="data-content-null d-flex j-center a-center">{{lastTwoDays(item.recordDate)}}未记录～</view>
						</view>
						<view v-else class="data-content">
							<view class="data-content-date">{{lastTwoDays(item.recordDate)}}</view>
							<view :class="`data-content-info d-flex ${weightDifference(index)>0?'background-rise':'background-decline'}`">
								<view class="content-info-heat d-flex wrap">
									<view class="divider-vertical"></view>
									<view class="divider-level"></view>
									<view class="info-heat-piece">
										<view class="heat-piece-top" style="padding-top:43rpx;">
											<text class="piece-top-number">{{item.breakfast+item.lunch+item.dinner+item.addFood}}</text>
											<text class="piece-top-unit">千卡</text>
										</view>
										<view class="heat-piece-below d-flex a-center j-center">
											<view><i :class="`icon icon-a-sherureliangbeifen8 ${weightDifference(index)>0?'font-color-rise':'font-color-decline'}`" style="font-size: 30rpx;"></i></view>
											<text class="piece-below-text">摄入热量</text>
										</view>
									</view>
									<view class="info-heat-piece" >
										<view class="heat-piece-info">静息{{item.rest}}+运动{{item.sports}}</view>
										<view class="heat-piece-top">
											<text class="piece-top-number">{{item.rest + item.sports}}</text>
											<text class="piece-top-unit">千卡</text>
										</view>
										<view class="heat-piece-below d-flex a-center j-center">
											<view><i :class="`icon icon-a-xiaohaoreliangbeifen8 ${weightDifference(index)>0?'font-color-rise':'font-color-decline'}`" style="font-size: 30rpx;"></i></view>
											<text class="piece-below-text" style="padding-right: 2rpx;">消耗热量</text>
											<view v-if="imageConvertArray(item.sportsImg).length>0"><i :id="`consume-${index}-0`" @tap="previewImage(`consume-${index}-`,0,imageConvertArray(item.sportsImg))"  :class="`icon icon-tupianlv ${weightDifference(index)>0?'font-color-rise':'font-color-decline'}`" style="font-size: 28rpx;"></i></view>
										</view>
									</view>
									<view class="info-heat-piece">
										<view class="heat-piece-top" style="padding-top:28rpx;"><!--`${countDifference(item)<0?'+':countDifference(item)}`-->
											<text class="piece-top-number" :style="{color:countDifference(item)<0?'#A9492F':'#333333'}">{{`${countDifference(item)<0?'+':countDifference(item)}`}}</text>
											<text class="piece-top-unit" v-if="countDifference(item)>=0">千卡</text>
										</view>
										<view class="heat-piece-below d-flex a-center j-center">
											<!--
											<view><i class="icon icon-reliangcha piece-below-icon" :style="{color:countDifference(item)<0?'#A9492F':'#999999'}"></i></view>
											<text class="piece-below-text" :style="{color:countDifference(item)<0?'#A9492F':'#999999'}">热量差</text>
											-->
											<view><i :class="`icon icon-a-reliangchabeifen8 ${weightDifference(index)>0?'font-color-rise':'font-color-decline'}`" style="font-size: 30rpx;"></i></view>
											<view class="piece-below-text">热量差</view>
										</view>
									</view>
									<view class="info-heat-piece">
										<view class="heat-piece-top" style="padding-top:28rpx;">
											<text class="piece-top-number">{{item.water}}</text>
											<text class="piece-top-unit">ml</text>
										</view>
										<view class="heat-piece-below d-flex a-center j-center">
											<!--
											<view><i class="icon icon-yinshuiliang piece-below-icon"></i></view>
											-->
											<view><i :class="`icon icon-a-yinshuiliangbeifen8 ${weightDifference(index)>0?'font-color-rise':'font-color-decline'}`" style="font-size: 30rpx;"></i></view>
											<view class="piece-below-text">饮水量</view>
										</view>
									</view>
								</view>
								<view :class="`content-info-weight d-flex d-c a-center j-center ${weightDifference(index)>0?'font-color-rise':'font-color-decline'}`">
									<view class="divider"></view>
										<view class="info-weight-describe d-flex a-center j-center">
											<!--
											<view><i @tap="previewImage(imageConvertArray(item.sportsImg))" :class="`icon icon-tupianlv ${weightDifference(index)>0?'font-color-rise':'font-color-decline'}`" style="font-size: 28rpx;"></i></view>
											-->
											<view v-if="imageConvertArray(item.weightUrl).length>0"><i :id="`weight-${index}-0`" @tap="previewImage(`weight-${index}-`,0,imageConvertArray(item.weightUrl))" class="icon icon-tupianlv" style="font-size: 28rpx;"></i></view>
											<text class="weight-describe-text">体重</text>
											<!--
											<i class="icon icon-yijianzhong" :style="`font-size: 32rpx;${weightDifference(index)>0?'transform: scaleY(-1);':''}`"></i>
											-->
										</view>
										<template v-if="item.aimWeight>0">
											<view class="info-weight-number ">
												<text class="weight-number-weight">{{item.aimWeight}}</text>
												<text class="weight-number-unit">KG</text>
											</view>
											<view class="info-weight-gap" v-if="weightDifference(index)!=0">{{weightDifference(index)>0?'+':''}}{{weightDifference(index)}}kg</view>
											<view class="info-weight-gap" v-else>无变化</view>
											<view class="info-weight-describe d-flex a-center j-center">
												<text class="weight-describe-text" style="color: #999999;">较上次</text>
												<i class="icon icon-yijianzhong" :style="`font-size: 32rpx;${weightDifference(index)>0?'transform: scaleY(-1);':''}`"></i>
											</view>
										</template>
										<template v-else>
											<text class="null">未记录</text>
										</template>
								</view>
							</view>
						</view>
						<!--结尾-->
						<view v-if="isEnd(index).show" class="data-content">
							<view class="data-content-date">{{isEnd(index).title}}</view>
							<view class="data-content-null d-flex a-center j-center">
								<view class="left-null-text">{{isEnd(index).days>1?`共${isEnd(index).days}天未记录`:`当日未记录`}}</view>
							</view>
						</view>
					</template>
				</pullScroolView>
			</swiper-item>
			<!--趋势-->
			<swiper-item>
				
			</swiper-item>
		</swiper>
		<!--图片预览-->
		<imagePreview ref="preview" @onChange="imageChange"></imagePreview>
	</view>
</template>

<script setup lang="tsx" name="heatWeightRecord">
import { userData as userDataStore } from "@/store/userData";
import { ref } from "vue";
import { getHeatWeightRecord } from "@/api/api";
import { onLoad } from "@dcloudio/uni-app";
import moment from "moment";
import BigNumber from "bignumber.js";
import {imageConvertArray,getHDImages} from '@/utils/format';
import imagePreview from "@/components/imagePreview.vue";


const userData: any = userDataStore();
const goBack = () => {
	uni.navigateBack();
};
const tabs = ref(["数据","趋势"]);
const menuSelect = ref(0);//选中的菜单
//选中菜单变更时事件
const changeTabs = (index:number) =>{
	menuSelect.value = index;
}
const changeSwiper = (event:any) => {
	menuSelect.value = event.detail.current;
	//console.log(event.detail.current);
};
let dataPageData:any = ref({});
let dataParams = {
	userId:userData.id,
	page:1,
	rows:10
}
//页面加载完成后加载初始数据
onLoad(() => {
	dataRefresh();
});
const scroll = ref();
//下拉刷新数据
const dataRefresh = () => {
	dataParams.page = 1;//设置刷新时查询第一页
	getHeatWeightRecord(dataParams).then((res: any) => {
		if(res.success){
			dataParams.page++;//设置下一页
			dataPageData.value = res.data;
			setTimeout(()=>{
			    scroll.value.success();
			},500);
			firstThreeDays();
			console.log(dataPageData.value)
		}
		//console.log(res.data)
	}); 
}
const scrolltolower = () => {
	if(dataParams.page>=dataPageData.value.pages)return;
	getHeatWeightRecord(dataParams).then((res: any) => {
		dataParams.page++;//设置下一页
		dataPageData.value.list.push(...res.data.list)
	});
}
//格式化日期为“今天、昨天、或前天”
const lastTwoDays = (dateStr:string) =>{
	let date = moment(dateStr,"YYYY-MM-DD");
	let diff = Math.abs(moment().diff(date, "days"));
	let result = date.format('M月D日');
	switch(diff){
		case 0:  
		    result = "今天";
			break;
		case 1:
			result = "昨天";
			break;
		case 2:
		    result = "前天";
			break; 
	}
	return result;
}
//计算和上一次的体重差值
const weightDifference = (index:number) => {
	let list = dataPageData.value.list;
	if((index+1)>=list.length)return 0;//找不到上次记录差值为0；
	let aimWeight1 = list[index+1].aimWeight;
	let aimWeight2 = list[index].aimWeight;
	if(aimWeight1===0||aimWeight2==0)return 0;
	return new BigNumber(aimWeight2).minus(new BigNumber(aimWeight1)).toNumber();
}
//图片预览
const preview = ref();
const previewImage = (id:string,index:number,urls:any) => {
	uni.createSelectorQuery().select(`#${id}${index}`).boundingClientRect().exec((ret)=>{
		//e.callback(ret[0])
		let params = {
			startInfo:ret[0],//图片的初始大小与位置
			id:id,
			index:index,//当前图片地址
			urls:getHDImages(urls),//预览集合图片地址
		}
		preview.value.open(params);
	});
}
const imageChange = (e:any) => {
	try{
		uni.createSelectorQuery().select(`#${e.id}${e.index}`).boundingClientRect().exec((ret)=>{
			uni.$emit("imagePreviewUpdate",ret[0])
		});
	}catch(e){
		uni.$emit("imagePreviewUpdate",null)
	}
}

const countDifference = (obj:any) =>{
	return  (obj.rest + obj.sports) - (obj.breakfast + obj.lunch + obj.dinner + obj.addFood);
}
//补齐前三天
const firstThreeDays = () => {
	let list = dataPageData.value.list;
	for(let i=2;i>=0;i--){
		let targetDate = moment().subtract(i,'days').format("YYYY-MM-DD"); 
		list.unshift({
			//"groupId": "100017",
			//"groupUserClockResponseParam":null,
			"recordDate":targetDate
		});
	}
	for(let i=2;i>=0;i--){
		let targetDate = moment().subtract(i,'days').format("YYYY-MM-DD");
		let indices = list.reduce((accumulator:any, currentValue:any, index:number) => {  
		    if (currentValue.recordDate == targetDate) {  
		        accumulator.push(index);  
		    }  
		    return accumulator;  
		}, []);  
		if(indices.length==2){
			list[indices[0]] = JSON.parse(JSON.stringify(list[indices[1]]));
			list.splice(indices[1], 1); 
		}
	}
	if(list.length<4){
		for(let i=2;i>=0;i--){
			if(list[i].rest==null)list.splice(i, 1); 
		}
	}
}
//折叠显示未打卡
const isBreak = (index:number) => {
	let json = {
		show:false,
		title:'',
		days:0,
	};
	//从第三天开始
	if(index>2){
		let list = dataPageData.value.list;
		let startDate = moment(list[index-1].recordDate).format("YYYY-MM-DD");
		let endDate = moment(list[index].recordDate).format("YYYY-MM-DD");
		
		
		let diffInDays = moment(startDate).diff(moment(endDate), 'days');
		if(diffInDays==2){
			json.show = true;
			let days = moment(startDate).subtract(1, 'days').format("YYYY-MM-DD");  
			json.title = lastTwoDays(days);
			let diffInDays = moment(startDate).diff(moment(endDate), 'days');
			json.days = diffInDays -1 
		}
		if(diffInDays>2){
			json.show = true;
			let days = moment(startDate).subtract(2, 'days').format("YYYY-MM-DD"); 
			let showStartDate = moment(startDate).subtract(1, 'days').format("YYYY-MM-DD");
			json.title = lastTwoDays(days)+"-"+lastTwoDays(showStartDate);
			
			let diffInDays = moment(startDate).diff(moment(endDate), 'days');
			json.days = diffInDays -1 
		}
	}
	return json;
}
//显示结尾
const isEnd = (index:number) => {
	let json = {
		show:false,
		title:'',
		days:0,
	};
	let list = dataPageData.value.list;
	let end = dataPageData.value.list[index+1];
	if(end==null&&dataParams.page==dataPageData.value.pages&&list[index].recordDate!=dataPageData.value.userJoinTime){
		
		let startDate = moment(list[index-1].recordDate).format("YYYY-MM-DD");
		let endDate = dataPageData.value.userJoinTime;
		let diffInDays = moment(startDate).diff(moment(endDate), 'days');
		json.show = true;
		json.title = endDate+"（加入轻盈）"+"- "+lastTwoDays(startDate);
		json.days = diffInDays;
		
	}
	return json;
}
</script>

<style lang="scss" scoped>
@import "./heatWeightRecord.scss";
</style>

